//
//  AIGirlMsgChangeNameView.swift
//  AIGirl
//
//  Created by Rae on 2024/1/22.
//

import UIKit
import SwiftEntryKit

class AIGirlMsgChangeNameView: UIView, AnimationProtocol, AnimationDelegate {

    func animationContainerViewSize() -> CGSize {
        CGSize(width: .screenWidth, height: .screenHeight)
    }
    
    func animationContainerViewStyle() -> AnimationViewStyle {
        .bottom
    }
    
    private lazy var titleLabel = c_make_ex(UILabel.self)
        .color(.white).font(17.font_medium).alignment(.center)
        .text("Set a name for your girl").end()
    private lazy var nameTextField = c_make_ex(UITextField.self)
        .bgColor("#A3A3A3".toColor.alpha(0.2)).corner(22)
        .color(.white).font(14.font_medium).alignment(.center)
        .placeholder("Enter your nicknime").end()
    private lazy var agetitleLabel = c_make_ex(UILabel.self)
        .color(.white).font(17.font_medium).alignment(.center)
        .text("How old is your sweetheart?").end()
    private lazy var selView = c_make_ex(UIView.self)
        .bgColor(.black.alpha(0.31)).corner(30).border("#C027FF", width: 2).end()
    private let collectionView = UICollectionView(frame: .zero, collectionViewLayout: MateKingAgeFlowLayout())
    private lazy var nextButton = c_make_ex(AIGirlSubmitButton.self)
        .color(.white).font(21.font_bold).corner(20)
        .text("Save").end()
    var observer: NSObjectProtocol!
    private var dataArray: [AIGirlSignInAgeModel] = {
        var data = [AIGirlSignInAgeModel]()
        for index in 0..<43 {
            let age = String(index + 18)
            var isSel = false
            if index == 0 {
                isSel = true
            }
            let model = AIGirlSignInAgeModel(age: age,isSel: isSel)
            data.append(model)
        }
        return data
    }()
    
    var saveClosure: ((_ nameStr: String) -> Void)?
    var dismissClosure: (() -> Void)?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        backgroundColor = .black.alpha(0.4)
        
        subviews{
            titleLabel
            nameTextField
            agetitleLabel
            selView
            collectionView
            nextButton
        }
        
        titleLabel.top(.navi_height + 110).centerHorizontally()
        nameTextField.height(44).width(300).centerHorizontally()
        nameTextField.Top == titleLabel.Bottom + 20
        agetitleLabel.centerHorizontally()
        agetitleLabel.Top == nameTextField.Bottom + 20
        collectionView.leading(0).trailing(0).height(60)
        collectionView.Top == agetitleLabel.Bottom + 20
        nextButton.height(50).width(300).centerHorizontally()
        nextButton.Top == collectionView.Bottom + 65
        
        selView.size(60).centerHorizontally()
        selView.CenterY == collectionView.CenterY
        
        nameTextField.placehold("#DBDBDB".toColor, font: 14.font_medium)
        observer = NotificationCenter.default.addObserver(forName: UITextField.textDidChangeNotification, object: nameTextField, queue: .main) { [weak self] notification in
            guard let strongSelf = self else { return }
            if let text = strongSelf.nameTextField.text, text.count > 20 {
                strongSelf.nameTextField.text = String(text.prefix(20)) // 截断过长的文本
            }
        }
//        let layout = UICollectionViewFlowLayout()
//        layout.scrollDirection = .horizontal
//        layout.minimumLineSpacing = 15
//        layout.minimumInteritemSpacing = 15
//        layout.itemSize = CGSize(width: 60, height: 60)
//        layout.sectionInset = UIEdgeInsets(top: 0, left: 100.0, bottom: 0, right: 0)
        collectionView.style { v in
            let margin = (CGFloat.screenWidth - 60) / 2
            v.contentInset = UIEdgeInsets(top: 0, left: margin, bottom: 0, right: margin)
//            v.collectionViewLayout = layout
            v.backgroundColor = .clear
            v.register(AIGirlAgeItem.self, forCellWithReuseIdentifier: AIGirlAgeItem.description())
            v.showsHorizontalScrollIndicator = false
            v.delegate = self
            v.dataSource = self
        }
        nextButton.addTarget(self, action: #selector(clickSaveButton), for: .touchUpInside)
        
        if let name = UserDefaultsManager.getString(forKey: .grilName) {
            nameTextField.text = name
        }
        
    }
    
    
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        dismissClosure?()
    }
    
    @objc private func clickSaveButton(){
        
        guard let name = nameTextField.text, name.count > 0 else {
            "Please set a name for your girl!".toast_error
            return
        }
        for model in dataArray {
            if model.isSel {
                UserDefaultsManager.setString(model.age, forKey: .grilAge)
            }
        }
        saveClosure?(name)
    }
    
    func loadAge(){
        if let age = UserDefaultsManager.getString(forKey: .grilAge) {
            let ageInt = age.intValue
            let index = ageInt - 18
            var models = [AIGirlSignInAgeModel]()
            dataArray.forEach { model in
                var itemModel = model
                itemModel.isSel = false
                models.append(itemModel)
            }
            models[index].isSel = true
            dataArray = models
            collectionView.reloadData()
            self.collectionView.scrollToItem(at: IndexPath.init(item: index, section: 0), at: .left, animated: false)
        }
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        loadAge()
    }
}

extension AIGirlMsgChangeNameView: UICollectionViewDelegate, UICollectionViewDataSource{
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dataArray.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        guard let item = collectionView.dequeueReusableCell(withReuseIdentifier: AIGirlAgeItem.description(), for: indexPath) as? AIGirlAgeItem else { return UICollectionViewCell() }
        item.model = dataArray[indexPath.row]
        return item
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        var models = [AIGirlSignInAgeModel]()
        dataArray.forEach { model in
            var itemModel = model
            itemModel.isSel = false
            models.append(itemModel)
        }
        models[indexPath.row].isSel = true
        dataArray = models
        collectionView.reloadData()
    }
}
